﻿using System;
using System.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;

namespace RecorderWorkerRole
{
    public class RecordingsBlobStorage
    {
        private static CloudStorageAccount _storageAccount = null;
        private static CloudBlobContainer _cloudBlobContainer;
        private static String _storageContainerName = "ceskyrozhlas-default";

        public static bool IsStaging()
        {
            //this method breaks an idea of staging - when we can swap it with production
            //return false;
            return _storageContainerName.Contains("staging");
        }

        public static void Init()
        {
            _storageAccount = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("BlobsConnectionString"));
            _storageContainerName = RoleEnvironment.GetConfigurationSettingValue("StorageContainerName");
            // Create the blob client.
            var aBlobClient = _storageAccount.CreateCloudBlobClient();
            // Create the container if it doesn't exist yet .
            _cloudBlobContainer = aBlobClient.GetContainerReference(_storageContainerName);
            _cloudBlobContainer.CreateIfNotExists(BlobContainerPublicAccessType.Blob);
        }

        public static String UploadToBlob(DownloadDetails aCurrentDownload)
        {

            CloudBlockBlob aTargetBlobRef = null;
            try
            {
                aTargetBlobRef = _cloudBlobContainer.GetBlockBlobReference(aCurrentDownload.HumanReadableName);
                Trace.TraceInformation("UPLOADING:  {0} : {1:N0} bytes total, {2}", aCurrentDownload, aCurrentDownload.Length, CustomDatesFormatter.GetPrintable(DateTime.UtcNow));
                aTargetBlobRef.UploadFromByteArray(aCurrentDownload.DownloadedBytes, 0, aCurrentDownload.Length);
                Trace.TraceInformation("DONE:  {0} : {1}, {2}", aCurrentDownload, aTargetBlobRef.SnapshotQualifiedUri.AbsoluteUri, CustomDatesFormatter.GetPrintable(DateTime.UtcNow));
                return aTargetBlobRef.SnapshotQualifiedUri.AbsoluteUri;
            }
            catch (Exception exc)
            {
                Trace.TraceInformation("FAILed to upload {0}  :  {1}  : {2}{3}",
                    aCurrentDownload, aCurrentDownload.StreamUri, exc, DestroyTargetBlob(aTargetBlobRef));
                throw;
            }
        }

        private static string DestroyTargetBlob(CloudBlockBlob aTargetBlobRef)
        {
            string additionalInfo="";
            if (aTargetBlobRef != null && aTargetBlobRef.Properties != null)
            {
                additionalInfo = String.Format("; {0} bytes downloaded", aTargetBlobRef.Properties.Length);
                aTargetBlobRef.DeleteIfExists();
            }
            return additionalInfo;
        }
    }
}